import defaultSettings from '@/settings'

const {
  isDark,
  isGrey,
  sideTheme,
  showSettings,
  topNav,
  tagsView,
  tagsViewIcon,
  fixedHeader,
  sidebarLogo,
  dynamicTitle,
  breadcrumbIcon,
  accordion
} = defaultSettings

const storageSetting = JSON.parse(localStorage.getItem('layout-setting')) || ''

const states = {
  title: '',
  theme: storageSetting.theme || '#1C53D9',
  isDark: storageSetting.isDark === undefined ? isDark : storageSetting.isDark,
  isGrey: storageSetting.isGrey === undefined ? isGrey : storageSetting.isGrey,
  sideTheme: storageSetting.sideTheme || sideTheme,
  showSettings,
  topNav: storageSetting.topNav === undefined ? topNav : storageSetting.topNav,
  tagsView: storageSetting.tagsView === undefined ? tagsView : storageSetting.tagsView,
  tagsViewIcon: storageSetting.tagsViewIcon === undefined ? tagsViewIcon : storageSetting.tagsViewIcon,
  fixedHeader: storageSetting.fixedHeader === undefined ? fixedHeader : storageSetting.fixedHeader,
  sidebarLogo: storageSetting.sidebarLogo === undefined ? sidebarLogo : storageSetting.sidebarLogo,
  dynamicTitle: storageSetting.dynamicTitle === undefined ? dynamicTitle : storageSetting.dynamicTitle,
  breadcrumbIcon: storageSetting.breadcrumbIcon === undefined ? breadcrumbIcon : storageSetting.breadcrumbIcon,
  accordion: storageSetting.accordion === undefined ? accordion : storageSetting.accordion
}

const mutations = {
  CHANGE_SETTING: (state, { key, value }) => {
    // eslint-disable-next-line no-prototype-builtins
    if (state.hasOwnProperty(key)) {
      state[key] = value
    }
  }
}

const actions = {
  // 修改布局设置
  changeSetting({ commit }, data) {
    commit('CHANGE_SETTING', data)
  },

  // 设置网页标题
  setTitle({ commit }, title) {
    states.title = title
  },

  // 灰色和弱色切换
  changeGreyOrWeak({ commit }, { type, value }) {
    const body = document.body
    if (!value) return body.removeAttribute('style')
    const styles = {
      grey: 'filter: grayscale(1)',
      weak: 'filter: invert(80%)'
    }
    body.setAttribute('style', styles[type])
  }
}

export default {
  namespaced: true,
  state: states,
  mutations,
  actions
}
